package com.lcj.eduService.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lcj.eduService.entity.EduSubject;
import com.lcj.eduService.entity.excel.ExcelSubjectData;
import com.lcj.eduService.entity.subject.OneSubject;
import com.lcj.eduService.entity.subject.TwoSubject;
import com.lcj.eduService.listener.SubjectListener;
import com.lcj.eduService.mapper.EduSubjectMapper;
import com.lcj.eduService.service.EduSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2021-03-10
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    //添加课程分类
    @Override
    public void saveSubject(MultipartFile file, EduSubjectService eduSubjectService) {

       try{
           //文件输入流
           InputStream in=file.getInputStream();

           //调用方法进行读取
           EasyExcel.read(in, ExcelSubjectData.class,new SubjectListener(eduSubjectService)).sheet().doRead();
       } catch (IOException e) {
           e.printStackTrace();
       }
    }

    //课程分类列表
    @Override
    public List<OneSubject> getAllOneTwoSubject() {
        //查询一级分类
        QueryWrapper<EduSubject> wrapperOne= new QueryWrapper<>();
        wrapperOne.eq("parent_id","0");
        List<EduSubject> oneSubjectList = baseMapper.selectList(wrapperOne);

        //查询二级分类
        QueryWrapper<EduSubject> wrapperTwo= new QueryWrapper<>();
        wrapperOne.ne("parent_id","0");
        List<EduSubject> twoSubjectList = baseMapper.selectList(wrapperTwo);

        //组装数据
        List<OneSubject> finalSUbject = new ArrayList<>();
        for (EduSubject eduSubject : oneSubjectList) {
            OneSubject oneSubject=new OneSubject();
            BeanUtils.copyProperties(eduSubject,oneSubject);
            finalSUbject.add(oneSubject);

            //封装二级分类
            List<TwoSubject> twoSubjects = new ArrayList<>();
            for (EduSubject subject : twoSubjectList) {
                if(subject.getParentId().equals(eduSubject.getId())){
                    TwoSubject twoSubject=new TwoSubject();
                    BeanUtils.copyProperties(subject,twoSubject);
                    twoSubjects.add(twoSubject);
                }
            }
            oneSubject.setChildren(twoSubjects);
        }

        return finalSUbject;
    }
}
